package com.sunbo509.www.gridview;

import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.support.v4.view.PagerAdapter;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.maps.AMap;
import com.amap.api.maps.MapView;
import com.amap.api.maps.model.BitmapDescriptorFactory;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.Marker;

import com.amap.api.maps.model.MarkerOptions;

import com.amap.api.maps.model.MyLocationStyle;
import com.amap.api.services.core.AMapException;
import com.amap.api.services.core.LatLonPoint;
import com.amap.api.services.core.PoiItem;
import com.amap.api.services.core.SuggestionCity;
import com.amap.api.services.poisearch.PoiResult;
import com.amap.api.services.poisearch.PoiSearch;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

import static com.amap.api.maps2d.AMap.MAP_TYPE_NORMAL;
import static com.autonavi.ae.pos.LocManager.init;

public class LocationActivity extends AppCompatActivity implements PoiSearch.OnPoiSearchListener, TextWatcher {

    private MapView mapView;
    private TextView tv_loc;
    private Button btn_loc;

    private EditText et_search;
    private RecyclerView recy;
    private String keyWord = "";// 要输入的poi搜索关键字
    private PoiResult poiResult; // poi返回的结果
    private int currentPage = 0;// 当前页面，从0开始计数
    private PoiSearch.Query query;// Poi查询条件类
    private PoiSearch     poiSearch;// POI搜索

    private MarkerOptions markerOption;
    private AMap aMap;
    Marker marker;
    private MarkerOptions markerOption1;
    private MarkerOptions markerOption2;
    private MarkerOptions markerOption3;
    private List<MarkerOptions>list=new ArrayList<>();
    private LatLng latlng = new LatLng(39.761, 116.434);
    private LatLng latlng1=new LatLng(39.851,116.332);
    private LatLng latLng2=new LatLng(39.941,116.230);
    private LatLng latLng3=new LatLng(39.631,116.128);


    private AMapLocationClient mapLocationClient=null;
    private AMapLocationClientOption option;
    private AMapLocationListener locationListener=new AMapLocationListener() {
        @Override
        public void onLocationChanged(AMapLocation aMapLocation) {
            if(aMapLocation!=null){
                String da=sHA1(getApplicationContext());
                if(aMapLocation.getErrorCode()==0){
                    aMapLocation.getLatitude();//纬度
                    aMapLocation.getLongitude();//经度
                    aMapLocation.getCountry();
                    aMapLocation.getProvince();
                    aMapLocation.getCity();
                    aMapLocation.getDistrict();
                    aMapLocation.getStreet();
                    aMapLocation.getStreetNum();
                    tv_loc.setText(aMapLocation.getCountry()+ aMapLocation.getProvince()
                            +aMapLocation.getCity()+aMapLocation.getDistrict()+
                            aMapLocation.getStreet()+ aMapLocation.getStreetNum());
                }
                else{
                    //显示错误信息ErrCode是错误码，errInfo是错误信息，详见错误码表。
                    Log.e("AmapError", "location Error, ErrCode:"
                            + aMapLocation.getErrorCode() + ", errInfo:"
                            + aMapLocation.getErrorInfo());
                    mapLocationClient.stopLocation();
                }
            }
        }
    };

    public LocationActivity() {
    }


    public static String sHA1(Context context) {
        try {
            PackageInfo info = context.getPackageManager().getPackageInfo(
                    context.getPackageName(), PackageManager.GET_SIGNATURES);
            byte[] cert = info.signatures[0].toByteArray();
            MessageDigest md = MessageDigest.getInstance("SHA1");
            byte[] publicKey = md.digest(cert);
            StringBuffer hexString = new StringBuffer();
            for (int i = 0; i < publicKey.length; i++) {
                String appendString = Integer.toHexString(0xFF & publicKey[i])
                        .toUpperCase(Locale.US);
                if (appendString.length() == 1)
                    hexString.append("0");
                hexString.append(appendString);
                hexString.append(":");
            }
            String result= hexString.toString();
            return result.substring(0, result.length()-1);
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return null;
    }


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_location);
        mapView=(MapView)findViewById(R.id.map);
        tv_loc=(TextView)findViewById(R.id.textView2);
        et_search=(EditText)findViewById(R.id.search);
        recy=(RecyclerView)findViewById(R.id.recy);
        btn_loc=(Button)findViewById(R.id.button);
        //地图方法必须重写
//         mapView.onCreate(savedInstanceState);
        mapView.onCreate(savedInstanceState);
        init();


//        // 定义北京市经纬度坐标（此处以北京坐标为例）
//        LatLng centerBJPoint= new LatLng(14.904989,126.405285);
//// 定义了一个配置 AMap 对象的参数类
//        AMapOptions mapOptions = new AMapOptions();
//// 设置了一个可视范围的初始化位置
//// CameraPosition 第一个参数： 目标位置的屏幕中心点经纬度坐标。
//// CameraPosition 第二个参数： 目标可视区域的缩放级别
//// CameraPosition 第三个参数： 目标可视区域的倾斜度，以角度为单位。
//// CameraPosition 第四个参数： 可视区域指向的方向，以角度为单位，从正北向顺时针方向计算，从0度到360度
//        mapOptions.camera(new CameraPosition(centerBJPoint, 10f, 100, 100));
//// 定义一个 MapView 对象，构造方法中传入 mapOptions 参数类
//         mapView = new MapView(getApplication(), mapOptions);
//
//// 调用 onCreate方法 对 MapView LayoutParams 设置
        //搜索的点击监听
        et_search.addTextChangedListener(this);
        //定位初始化
        mapLocationClient=new AMapLocationClient(getApplicationContext());
        mapLocationClient.setLocationListener(locationListener);
        option=new AMapLocationClientOption();
        option.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
        option.setInterval(2000);
        mapLocationClient.setLocationOption(option);
        btn_loc.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                 mapLocationClient.startLocation();
            }
        });
        //marker初始化
        aMap = mapView.getMap();
        MyLocationStyle myLocationStyle = new MyLocationStyle();
        myLocationStyle.strokeColor(Color.TRANSPARENT);// 设置圆形的边框颜色
        myLocationStyle.radiusFillColor(Color.argb(0, 0, 0, 0));// 设置圆形的填充颜色
        myLocationStyle.strokeWidth(3.0f);// 设置圆形的边框粗细
        aMap.setMyLocationStyle(myLocationStyle);
        aMap.getUiSettings().setMyLocationButtonEnabled(true);
//        aMap.moveCamera(CameraUpdateFactory.newLatLngZoom( 4));
        aMap.setMapType(MAP_TYPE_NORMAL);
    }

    /**
     * 初始化AMap对象
     */
    private void init() {
//        Button clearMap = (Button) findViewById(R.id.clearMap);
//        clearMap.setOnClickListener(this);
//        Button resetMap = (Button) findViewById(R.id.resetMap);
//        resetMap.setOnClickListener(this);
        if (aMap == null) {
            aMap = mapView.getMap();
            addMarkersToMap();// 往地图上添加marker
        }
    }

    /**
     * 在地图上添加marker
     */
    private void addMarkersToMap() {
        markerOption = new MarkerOptions().icon(BitmapDescriptorFactory.fromResource(R.drawable.lanse))
                .position(latlng)
                .draggable(true);
        list.add(markerOption);
        markerOption1 = new MarkerOptions().icon(BitmapDescriptorFactory.fromResource(R.drawable.lanse))
                .position(latlng1)
                .draggable(true);
        list.add(markerOption1);
        markerOption2 = new MarkerOptions().icon(BitmapDescriptorFactory.fromResource(R.drawable.lanse))
                .position(latLng2)
                .draggable(true);
        list.add(markerOption2);
        markerOption3 = new MarkerOptions().icon(BitmapDescriptorFactory.fromResource(R.drawable.lanse))
                .position(latLng3)
                .draggable(true);
        list.add(markerOption3);
       for (int i=0;i<list.size();i++) {
//           MarkerOptions marker=list.get(i);
           aMap.addMarker(list.get(i));
       }
    }

    //地图方法必须重写
    @Override
    protected void onDestroy() {
        super.onDestroy();
        mapView.onDestroy();
    }
    //地图方法必须重写
    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        mapView.onSaveInstanceState(outState);
    }
    //地图方法必须重写
    @Override
    protected void onPause() {
        super.onPause();
        mapView.onPause();
    }
    //地图方法必须重写
    @Override
    protected void onResume() {
        super.onResume();
        mapView.onResume();
    }


//搜索
    @Override
    public void onPoiSearched(PoiResult poiResult, int i) {
        if (i == AMapException.CODE_AMAP_SUCCESS) {
            if (poiResult != null && poiResult.getQuery() != null) {  // 搜索poi的结果
                if (poiResult.getQuery().equals(query)) {  // 是否是同一条
                    poiResult = poiResult;
                    ArrayList<PoiAddressBean> data = new ArrayList<PoiAddressBean>();//自己创建的数据集合
                    // 取得搜索到的poiitems有多少页
                    List<PoiItem> poiItems = poiResult.getPois();// 取得第一页的poiitem数据，页数从数字0开始
                    List<SuggestionCity> suggestionCities = poiResult
                            .getSearchSuggestionCitys();// 当搜索不到poiitem数据时，会返回含有搜索关键字的城市信息
                    for(PoiItem item : poiItems){
                        //获取经纬度对象
                        LatLonPoint llp = item.getLatLonPoint();
                        double lon = llp.getLongitude();
                        double lat = llp.getLatitude();

                        String title = item.getTitle();
                        String text = item.getSnippet();
                        String provinceName = item.getProvinceName();
                        String cityName = item.getCityName();
                        String adName = item.getAdName();
                        data.add(new PoiAddressBean(String.valueOf(lon), String.valueOf(lat), title, text,provinceName,
                                cityName,adName));
                    }
                    PoiKeywordSearchAdapter adapter = new PoiKeywordSearchAdapter(LocationActivity.this,data);
                   recy.setAdapter(adapter);
                }
            } else {
                Toast.makeText(getApplicationContext(),"没有结果",Toast.LENGTH_LONG).show();
            }
        } else {
            Toast.makeText(getApplicationContext(),"错误码"+i,Toast.LENGTH_LONG).show();
        }

    }

    @Override
    public void onPoiItemSearched(PoiItem poiItem, int i) {

    }


    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {
        keyWord = String.valueOf(s);
        if ("".equals(keyWord)) {
            Toast.makeText(getApplicationContext(),"请输入要搜索的关键字",Toast.LENGTH_LONG).show();
            return;
        } else {
            doSearchQuery();
            recy.setLayoutManager(new LinearLayoutManager(this));
        }

    }

    private void doSearchQuery() {
        currentPage = 0;
        //不输入城市名称有些地方搜索不到
        query = new PoiSearch.Query(keyWord, "", "大连");// 第一个参数表示搜索字符串，第二个参数表示poi搜索类型，第三个参数表示poi搜索区域（空字符串代表全国）
        //这里没有做分页加载了,默认给50条数据
        query.setPageSize(50);// 设置每页最多返回多少条poiitem
        query.setPageNum(currentPage);// 设置查第一页

        poiSearch = new PoiSearch(this, query);
        poiSearch.setOnPoiSearchListener(this);
        poiSearch.searchPOIAsyn();
    }

    @Override
    public void afterTextChanged(Editable s) {

    }

    public void setDetailAddress(String detailAddress) {
        et_search.setText(detailAddress);
    }
}
